package com.atguigu.shiro.ScheduledTask;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 静态定时任务
 */
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class StaticScheduledTask {

    //3.添加定时任务
    @Async //异步执行 不用等前面任务执行完毕再执行
    //https://www.pppet.net/ 在线Cron表达式生成器
    @Scheduled(cron = "0/30 0/1 * * * ?")
    public void scheduledTask(){
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime ldt = LocalDateTime.now();
        String format = ldt.format(dtf);
        System.out.println("当前时间" + format);
    }

    /**
     * 使用Timer
     */
    public void timer2(){
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.out.println("TimerTask:当前时间" + new Date());
            }
        };
        Timer timer = new Timer();
        timer.schedule(timerTask,10,1000);
    }

    /**
     * 使用ScheduledExecutorService
     */
    public void timer3(){
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        scheduledExecutorService.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("ScheduledExecutorService:当前时间" + new Date());
            }
        },2, TimeUnit.MINUTES);
    }

}
